package com.zoe.onelink.auth.endpoint;

import cn.hutool.core.util.StrUtil;
import com.zoe.onelink.auth.annotation.InnerUrl;
import com.zoe.onelink.auth.endpoint.dto.FlushAuthInfoDto;
import com.zoe.onelink.auth.endpoint.dto.FlushPermissionDto;
import com.zoe.onelink.common.model.ApiResult;
import com.zoe.onelink.upms.common.entity.AuthInfo;
import com.zoe.onelink.upms.common.service.OneLinkTokenStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2018</p>
 * <p>公司: 智业软件</p>
 *
 * @author LinHongKai
 * @date 2022-03-17 13:59
 */
@Slf4j
@RestController
@RequestMapping("/inner/client")
@ApiIgnore
@InnerUrl
public class ClientEndPoint {


    @Autowired
    private OneLinkTokenStore oneLinkTokenStore;


    @PostMapping(value = "/cleanToken")
    public ApiResult<Boolean> cleanToken(@RequestParam(value = "accessToken") String accessToken){
        OAuth2AccessToken oAuth2AccessToken = oneLinkTokenStore.readAccessToken(accessToken);
        if(oAuth2AccessToken == null){
            return new ApiResult<>(true);
        }
        // 清空access token
        oneLinkTokenStore.removeAccessToken(oAuth2AccessToken);
        // 清空refresh token
        oneLinkTokenStore.removeRefreshToken(oAuth2AccessToken.getRefreshToken());
        return new ApiResult<>(true);
    }


    @PostMapping(value = "/flushAuthInfo")
    public ApiResult<Boolean> flushAuthInfo(@RequestBody FlushAuthInfoDto dto){
        if(dto == null || StrUtil.isEmpty(dto.getAuthInfoValue())){
            return new ApiResult<>(true);
        }
        AuthInfo authInfo = oneLinkTokenStore.deserialize(dto.getAuthInfoValue(), AuthInfo.class);
        oneLinkTokenStore.flushAuthInfo(authInfo);
        return new ApiResult<>(true);
    }


    @PostMapping(value = "/flushPermission")
    public ApiResult<Boolean> flushPermission(@RequestBody FlushPermissionDto dto){
        OAuth2AccessToken accessToken = oneLinkTokenStore.readAccessToken(dto.getToken());
        if (accessToken == null) {
            return new ApiResult<>(true);
        }
        List<String> permissions = null;
        if (StrUtil.isNotEmpty(dto.getPermissionsValue())) {
            permissions = Arrays.asList(dto.getPermissionsValue().split(","));
        }
        oneLinkTokenStore.flushPermission(accessToken, permissions);
        return new ApiResult<>(true);
    }
}
